package cmd

import (
	"gitee.com/igolang/pkg/boot"
	"gitee.com/igolang/pkg/xcfg"
	"gitee.com/igolang/pkg/xcommand"
	"gitee.com/igolang/pkg/xlog"
	"gitee.com/igolang/pkg/xutils"
	"github.com/spf13/cobra"
	"os"
	"path/filepath"
)

const (
	defaultConfigDir = "config"
	flagCfgFile      = "xcfg.file"
	flagCfgPath      = "xcfg.path"
)

var (
	log              = xlog.DefaultStdLog()
	cfgFile, cfgPath string
)

var rootCmd = &cobra.Command{
	PersistentPreRun: func(cmd *cobra.Command, args []string) {
		// 初始化配置
		if err := initConfig(); err != nil {
			log.Panicln(err, cmd.Help())
		}
	},
}

func Run() {
	if err := rootCmd.Execute(); err != nil {
		log.Panicln(err)
	}
}

func init() {
	// 设置时区,东八区
	//cstZone := time.FixedZone("CST", 8*3600)
	//time.Local = cstZone
	xcommand.Init(os.Args...)
	rootCmd.PersistentFlags().StringVar(&cfgFile, flagCfgFile, xcommand.GetOptWithEnv(flagCfgFile), "设置配置文件绝对路径")
	rootCmd.PersistentFlags().StringVar(&cfgPath, flagCfgPath, xcommand.GetOptWithEnv(flagCfgPath), "设置配置目录绝对路径")
	rootCmd.Version = boot.Info().String()
	rootCmd.AddCommand(versionCmd)
	rootCmd.AddCommand(genCmd)
	rootCmd.AddCommand(httpCmd)
	rootCmd.AddCommand(demoCmd)
}

func initConfig() error {
	if cfgFile != "" {
		xcfg.SetFile(cfgFile)
	}
	if cfgPath != "" {
		xcfg.SetDir(cfgPath)
	}

	// 尝试从运行目录中寻找
	if cfgFile == "" && cfgPath == "" {
		xcfg.SetDir(filepath.Join(
			xutils.CurrentAbPath(),
			defaultConfigDir,
		))
	}
	if err := xcfg.Init(); err != nil {
		return err
	}
	log.Println("init config", xcfg.GetFile(), xcfg.GetDir())
	return nil
}
